package com.heima.article.service.impl;

import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFegin;
import com.heima.feigns.AuthorFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.sun.xml.internal.bind.v2.TODO;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author lo
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    AdminFegin adminFegin;


    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    GeneratePageService generatePageService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.minio.readPath}")
    String readPath;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    /**
     * 发布文章
     * 根据文章id保存或者修改文章信息
     *
     * @param newsId 文章id
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void publishArticle(Integer newsId) {
        //1.校验参数
        if (newsId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.查询wmNews

        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        if (wmNewsById == null || !wmNewsById.getCode().equals(0)) {
            log.error("文章发布失败 文章状态不为 4 或 8， 不予发布 , 文章id : {}", newsId);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "远程调用wemediaFeign失败");
        }
        WmNews wmNews = wmNewsById.getData();
        //判断文章状态必须是 ,8:审核通过,4 :人工审核通过
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_AUTHED_STATUS)) {
            if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_MANPOWER_PASS_STATUS)) {
                log.error("文章发布失败, 文章状态不对,审核通过之后才能发布");
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "审核通过之后才能发布");
            }
        }

        //3.根据WmNews文章信息封装ApArticle数据
        ApArticle apArticle = getApArticle(wmNews);
        //4.保存或修改文章信息
        saveOrUpdateApArticle(apArticle);
        //5.保存配置信息和内容信息
        saveConfigAndContent(apArticle, wmNews);
        //6.TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        //7. 更新 wmNews状态  改为9  并设置articleId
        updateWmNews(wmNews, apArticle, newsId);

        //TODO: 通知es 索引库添加文章索引
    }


    /**
     * 更新WmNews文章状态
     *
     * @param wmNews    自媒体文章
     * @param apArticle 发布文章
     * @param newsId    文章id
     */
    private void updateWmNews(WmNews wmNews, ApArticle apArticle, Integer newsId) {
        //将wmnews状态设置为9
        wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
        //远程调用更信息状态
        ResponseResult updateWmNews = wemediaFeign.updateWmNews(wmNews);
        if (!updateWmNews.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");
        }
    }

    /**
     * 保存配置信息和内容信息
     * 4.封装ApArticleConfig表信息
     * 5.封装ApArticleContent表信息
     *
     * @param apArticle
     */
    private void saveConfigAndContent(ApArticle apArticle, WmNews wmNews) {
        // 添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        // 文章id
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        // 添加文章详情
        ApArticleContent apArticleContent = new ApArticleContent();
        //文章id
        apArticleContent.setArticleId(apArticle.getId());
        //文章内容
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);

        wmNews.setArticleId(apArticle.getId());
        //自媒体文章信息
        if (apArticle.getId() != null) {
            //向自媒体文章表中添加文章id
            wemediaFeign.updateWmNews(wmNews);
        }

    }

    /**
     * 保存或修改文章信息
     *
     * @param apArticle
     */
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        //1.更具id 查询对应的文章是存在
        if (apArticle.getId() == null) {
            apArticle.setCollection(0);// 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            //说明文章不存在 保存文章信息
            save(apArticle);
        } else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle apArt = getById(apArticle.getId());
            if (apArt == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    /**
     * 封装ApArticle数据
     *
     * @param wmNews 自媒体文章信息
     *               1.需要WmNews信息
     *               2.需要AdChannel信息
     *               3.需要ApAuthor作者信息
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setLayout(wmNews.getType());//布局
        apArticle.setFlag((byte) 0);//文章类型
        apArticle.setId(wmNews.getArticleId());//文章id

        //根据id 查询频道信息系
        ResponseResult<AdChannel> adminFeginOne = adminFegin.findOne(wmNews.getChannelId());
        if (!adminFeginOne.checkCode()) {
            log.error("文章发布失败 远程调用查询频道出现异常， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用查询频道出现异常");
        }
        //封装频道信息
        AdChannel adChannel = adminFeginOne.getData();
        if (adChannel == null) {
            log.error("文章发布失败 未查询到相关频道信息， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到相关频道信息");
        }
        apArticle.setChannelId(adChannel.getId());
        apArticle.setChannelName(adChannel.getName());

        // 设置作者信息
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author == null) {
            log.error("文章发布失败 未查询到相关作者信息， 不予发布 , 文章id : {}  自媒体用户id : {}", wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "根据自媒体用户，查询关联作者信息失败");
        }

        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());
        return apArticle;
    }

    /**
     * app端查询文章列表
     * 加载文章
     *
     * @param loadtypeLoadMore 加载更多
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtypeLoadMore, ArticleHomeDTO dto) {

        //1.设置分页大小检查参数
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        //2.设置频道
        if (Strings.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //3.设置时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }

        //判断查询类型
        if (!loadtypeLoadMore.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                && loadtypeLoadMore.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            //既不是1 又不是 0 ,默认查询更多
            loadtypeLoadMore = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询前十条
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtypeLoadMore);
        //将前缀和真实路径进行拼接,能够访问到我们的静态页面
        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        ResponseResult result = ResponseResult.okResult(apArticles);
        return result;
    }

    /**
     * 根据参数加载文章列表  v2
     * @param loadtypeLoadMore
     * @param dto
     * @param firstPage
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage){
            //从redis中查
            String articleList = (String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            List<ApArticle> apArticles = JSON.parseArray(articleList, ApArticle.class);
            for (ApArticle apArticle : apArticles) {
                apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
            }
            ResponseResult result = ResponseResult.okResult(apArticles);
            result.setHost(webSite);
            return result;
        }
        //从mysql中查
        return load(loadtypeLoadMore,dto);
    }

}